package com.easyExcel.handler;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomAlignRightStrategy implements CellWriteHandler {
    private final List<String> rightAlignColumnNames;
    private final Map<String, CellStyle> cellStyleMap = new HashMap<>();
    public CustomAlignRightStrategy(List<String> rightAlignColumnNames) {
        this.rightAlignColumnNames = rightAlignColumnNames;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {

    }


        @Override
        public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
            if (isHead ||!rightAlignColumnNames.contains(head.getFieldName())) {
                return;
            }

            // 获取工作簿对象
//
//            Workbook workbook =  writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook();
//            // 创建一个新的样式
//            CellStyle newCellStyle = workbook.createCellStyle();
//            // 设置右对齐
//            newCellStyle.setAlignment(HorizontalAlignment.RIGHT);
//
//            // 应用新的样式到单元格
//            cell.setCellStyle(newCellStyle);

            Workbook workbook = writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook();
            String styleKey = "rightAlignStyle";
            CellStyle cellStyle = cellStyleMap.get(styleKey);
            if (cellStyle == null) {
                cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.RIGHT);
                cellStyleMap.put(styleKey, cellStyle);
            }

            cell.setCellStyle(cellStyle);
        }



    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {

    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {

    }

}